﻿using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Services;
using IntelligentAgriculture.WebAPI.Application.Command.UserCommand;
using IntelligentAgriculture.WebAPI.Controllers;
using MediatR;

namespace IntelligentAgriculture.WebAPI.Application.CommandHandler.UserCommandHandler
{
    public class UserLoginCommandHandler : IRequestHandler<UserLoginCommand, Results<Userinfo>>
    {
        private readonly IUserService _userService;
        private readonly TokenService _tokenService;
        private readonly ILogger<UserLoginCommandHandler> _logger;
        public UserLoginCommandHandler(IUserService userService, TokenService tokenService, ILogger<UserLoginCommandHandler> logger)
        {
            _userService = userService;
            _tokenService = tokenService;
            _logger = logger;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Results<Userinfo>> Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var userDto = _userService.Login(request.UserName, request.PassWord);
                if (userDto != null)
                {
                    _logger.LogInformation($"{userDto.NickName}登录了");
                    var token = _tokenService.GenerateToken(userDto);
                    return Results<Userinfo>.TokenResult(token, userDto);
                }
                _logger.LogError($"账号：{request.UserName}，密码：{request.PassWord}:登录失败：");
                return Results<Userinfo>.FailResult("用户或者密码不正确");
            }
            catch (Exception ex)
            {

                _logger.LogError("登录方法出错" + ex.Message);
                throw;
            }
        }
    }
}
